#include "SurfaceCache.h"

SurfaceCache* SurfaceCache::m_surfaceCache = NULL;

SurfaceCache::SurfaceCache()
{
    //ctor
}

SurfaceCache::~SurfaceCache()
{
    //dtor
}

/* GetSingleton */
SurfaceCache* SurfaceCache::GetSurfaceCache()
{
	if (not m_surfaceCache)
        m_surfaceCache = new SurfaceCache();
	return m_surfaceCache;
}

SDL_Surface* SurfaceCache::GetSurface(CRstring filename, bool &fromCache)
{
    SDL_Surface *surface;
    map<string, SDL_Surface*>::iterator iter;

    iter = m_Surfaces.find(filename);
    if (iter == m_Surfaces.end())
    {
        // Surface was not found, let's create it
        surface = IMG_Load(filename.c_str());
        m_Surfaces[filename] = surface;
        fromCache = false;
        return surface;
    } else {
        fromCache = true;
        return iter->second;
    }
}

void SurfaceCache::Clear()
{
    map<string,SDL_Surface*>::iterator I;
    for (I = m_Surfaces.begin(); I != m_Surfaces.end(); ++I)
    {
        SDL_FreeSurface((*I).second);
        (*I).second = NULL;
    }
    m_Surfaces.clear();
}
